package org.alex.nettychat.netty.first.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * 客户端写数据给服务端
 * @author : alex
 */
public class FirstClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 客户端连接建立成功之后被调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(LocalDateTime.now() +":客户端写出数据");
        // 1 获取数据
        ByteBuf buffer = getByteBuff(ctx);
        // 2 写数据
        ctx.channel().writeAndFlush(buffer);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;

        // 接受到服务端消息
        System.out.println(LocalDateTime.now() + ":客户端读取到的数据->" + byteBuf.toString(StandardCharsets.UTF_8));
    }

    private ByteBuf getByteBuff(ChannelHandlerContext ctx) {
        // 1 获取二进制ByteBuf
        ByteBuf buffer = ctx.alloc().buffer();
        // 2 准备数据，指定字符集为UTF-8
        byte[] bytes = "你好,Alex!".getBytes(StandardCharsets.UTF_8);
        // 3 填充数据到ByteBuf
        buffer.writeBytes(bytes);

        return buffer;
    }
}
